/*
 * @Author: your name
 * @Date: 2022-03-14 11:39:10
 * @LastEditTime: 2022-05-24 13:53:36
 * @LastEditors: liuhanlu liuhanlu@163.com
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \rongeduo-admin\src\utils\request.js
 */
import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 180000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      config.headers.Authorization = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    removeToken()
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    return response
  },
  error => {
    // 没有权限，跳转到登录
    if (error.message.indexOf('401') !== -1) {
      // window.location.href = '/baihui'
      // window.location.href = '/hxr'
      // window.location.href = '/login'
      async function logOut() {
        await this.$store.dispatch("user/logout");
        this.$router.push(`/login?redirect=${this.$route.fullPath}`);
      }
      logOut()
    }
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })

    return Promise.reject(error)
  }
)

export default service
